package com.qzimp.fujiancuo.advices;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.qzimp.fujiancuo.entity.vo.ResultCode;
import com.qzimp.fujiancuo.entity.vo.ResultVo;
import com.qzimp.fujiancuo.exceptions.ApiException;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;

@RestControllerAdvice(basePackages ={"com.qzimp.fujiancuo.controller","com.qzimp.fujiancuo.controller.api"})
public class ControllerResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // response是ResultVo类型，或者注释了NotControllerResponseAdvice都不进行包装
        return !returnType.getParameterType().isAssignableFrom(ResultVo.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        if (returnType.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 将数据包装在ResultVo里后转换为json串进行返回
                return objectMapper.writeValueAsString(new ResultVo(body));
            } catch (JsonProcessingException e) {
                throw new ApiException(ResultCode.RESPONSE_PACK_ERROR);
            }
        }
        if(Object.class.isAssignableFrom(returnType.getParameterType())){

            if (body==null){

                throw new ApiException(ResultCode.NO_DATA_ERROR); //自定义异常
            }

        }
        if(List.class.isAssignableFrom(returnType.getParameterType())){
            List data1=(List) body;
            if(data1.isEmpty()){
                 throw new ApiException(ResultCode.NO_DATA_ERROR); //自定义异常
//                return new ResultVo(ResultCode.NO_DATA_ERROR);
            }
            return new ResultVo(body);

        }

        return new ResultVo(body);
    }
}
